// example/querycar/querycar.js
import * as Api from '../../utils/api.js'
var app = getApp()
var twoPoint = {
  x1: 0,
  y1: 0,
  x2: 0,
  y2: 0
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    stv: {
      offsetX: 0,                                   //剪裁图片左上角坐标x
      offsetY: 0,                                   //剪裁图片左上角坐标y
      zoom: false,                                  //是否缩放状态
      distance: 0,                                  //两指距离
      scale: 1,                                     //缩放倍数
      rotate: 0                                     //旋转角度
    },
    themeColors: '',
    queryModel: false,
    returnList: [],
    vinStoryList: [],
    numVin: 0,
    vin: '',
    _num: 1,
    height: 0,
    showLayer: false,
    name_focus: true,
    name_fo: false,
    notVinMore: false,
    showImage: [],
    imageWidth: '',
    imageHeight: '',
    inputFocus: true,
    specialBtn: true,
    tapNum: true,
    isKeyboard: false,
    windowWidth: '',
    windowHeight: '',
    keyboardNumber: '1234567890',
    keyboardAlph: 'QWERTYUIOPASDFGHJKL巛ZXCVBNM',
    textArr: [],
    textValue: '',
    keyboard1: '',
    keyboard2: '',
    imgIcon: '',
    keyboard2For: [''],
    keyboardValue: '',
    id: 'cropper',
    width: '',
    height: '',
    imgLoad: false,
    minScale: 1,
    maxScale: 2.5,
    minRotateAngle: 45, //判断发生旋转的最小角度
    vinBoxList: [
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      },
      {
        val: '',
        select: false,
      }
    ],
    avatarIcon: '',
    ratio: 102 / 152,
    originUrl: '',
    cropperResult: ''
  },
  bindlongtap() {
    console.log(2)
  },
  imageLoad(e) {
    let originalWidth = e.detail.width;
    let originalHeight = e.detail.height;

    let attr = wx.getStorageSync('cameraImg') ? wx.getStorageSync('cameraImg') : false
    console.log(originalWidth)
    this.setData({
      imageWidth: parseInt(originalWidth),
      imageHeight: originalHeight,
      'stv.offsetY': attr ? -(parseInt(originalHeight / 2)) : 0,
      'stv.offsetX': attr ? -(parseInt(originalWidth / 4)) : 0,
      'stv.scale': attr ? 0.5 : 1
    });
    if (attr) {
      wx.removeStorageSync('cameraImg')
    }
  },
  //事件处理函数
  touchstartCallback: function (e) {
    if (e.touches.length === 1) {
      let { clientX, clientY } = e.touches[0];
      this.startX = clientX;
      this.startY = clientY;
      this.touchStartEvent = e.touches;
    } else {
      let xMove = e.touches[1].clientX - e.touches[0].clientX;
      let yMove = e.touches[1].clientY - e.touches[0].clientY;
      let distance = Math.sqrt(xMove * xMove + yMove * yMove);
      twoPoint.x1 = e.touches[0].pageX * 2
      twoPoint.y1 = e.touches[0].pageY * 2
      twoPoint.x2 = e.touches[1].pageX * 2
      twoPoint.y2 = e.touches[1].pageY * 2
      this.setData({
        'stv.distance': distance,
        'stv.zoom': true, //缩放状态
      })
    }
  },
  //图片手势动态缩放
  touchmoveCallback: function (e) {
    let _this = this
    fn(_this, e)
  },
  touchendCallback: function (e) {
    //触摸结束
    if (e.touches.length === 0) {
      this.setData({
        'stv.zoom': false, //重置缩放状态
      })
    }
  },




  // 情况历史记录
  closeHistoryFn() {
    console.log(55)
    let modelVin = this.data.vinStoryList
    wx.removeStorageSync('StoryItem')

    this.setData({
      vinStoryList: []
    })

  },
  clickHistoryFn(e) {
    console.log(e.currentTarget.dataset.vin)
    let data = e.currentTarget.dataset.vin
    console.log(data)
    let vinData = this.data.vinBoxList
    let attr = []
    for (let i = 0; i < data.length; i++) {
      console.log(data[i])
      vinData[i].val = data[i]
      vinData[i].select = false
    }

    this.setData({
      vinBoxList: vinData,
      vin: e.currentTarget.dataset.vin
    })
    this.goCategory()


  },
  showJianpanFn() {
    let flag = this.data.isKeyboard
    let data = this.data.vinBoxList
    console.log(data[0])
    console.log(flag)
    let attr = data.filter((item) => { return item.select })
    if (!attr.length) {
      data[0].select = flag ? false : true
    }
    // if (flag) {
    //   data.forEach(item => {
    //     item.select = false
    //   })
    // }

    console.log(data[0])
    this.setData({
      vinBoxList: data,
      isKeyboard: flag ? false : true
    })


  },
  uploadTap() {
    let _this = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        _this.setData({
          originUrl: res.tempFilePaths[0],
          cropperResult: ''
        })
      }
    })
  },
  getCropperImg(img) {
    console.log(img)
    let _this = this;

    let url = app.globalData.baseUrl1 + '/fileupload'
    let uploadTask = wx.uploadFile({
      url: url,
      filePath: img,
      name: 'file',
      success: function (res1) {
        console.log(res1)
        let opt = JSON.parse(res1.data)
        console.log(opt)
        console.log('返回的图片')
        _this.setData({
          originUrl: '',
          cropperResult: '',
          avatarIcon: opt.data.filename
        })
        // wx.showLoading({
        //   mask: true,
        //   title: '数据加载中'
        // })
        _this.imageToText(opt.data.filename)

      },
    })
  },
  setImgAvatar(e) {
    let _this = this
    console.log(typeof e.currentTarget.dataset.index)
    let attr = this.data.vinBoxList
    attr.forEach((it) => {
      it.val = ''
      it.select = false
    })
    switch (parseInt(e.currentTarget.dataset.index)) {
      case 1:
        _this.setData({
          cropperResult: '',
          vin: '',
          vinBoxList: attr
        })
        wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['camera'],
          success: function (res) {
            console.log(4545)
            _this.setData({
              originUrl: res.tempFilePaths[0],
              cropperResult: '',
              vin: '',
              vinBoxList: attr
            })
          }
        })
        break;
      case 2:
        _this.setData({
          cropperResult: '',
          vin: '',
          vinBoxList: attr
        })
        wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album'],
          success: function (res) {
            console.log(res.tempFilePaths)
            _this.setData({
              originUrl: res.tempFilePaths[0],
            })
          }
        })
        break;

    }
    this.setData({
      showLayer: false,
      avatarIcon: ''
    })
  },
  setInput() {
    this.setData({
      name_fo: false
    })
  },
  showImg() {
    wx.previewImage({
      current: '', // 当前显示图片的http链接
      urls: this.data.showImage // 需要预览的图片http链接列表
    })
  },

  // stv: {
  //   offsetX: 0,                                   //剪裁图片左上角坐标x
  //   offsetY: 0,                                   //剪裁图片左上角坐标y
  //   zoom: false,                                  //是否缩放状态
  //   distance: 0,                                  //两指距离
  //   scale: 1,                                     //缩放倍数
  //   rotate: 0                                     //旋转角度
  // },

  showImgLayer() {
    this.setData({
      inputFocus: false,
      'stv.offsetX': 0,
      'stv.offsetY': 0,
    })
    wx.navigateTo({
      url: '/pages/core/photo/photo'
    })

  },
  filterImage() {
    var self = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let url = app.globalData.baseUrl1 + '/fileupload'
        let uploadTask = wx.uploadFile({
          url: url,
          filePath: res.tempFilePaths[0],
          name: 'file',
          success: function (res1) {

            let opt = JSON.parse(res1.data)
            console.log(
              opt.data
            )
            let showImage = []
            showImage.push(opt.data.filename)
            self.setData({
              showImage: showImage
            })
            self.imageToText(opt.data.filename)
          },
        })

      }
    })


  },
  imageToText(pic) {
    let self = this
    let url = app.globalData.baseUrl1 + '/vinpic/qurey';
    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
      pic: pic
    }
    console.log(data)
    let callBack = (res) => {
      wx.hideLoading()
      this.setData({
        imgLoad: false
      })
      if (res == null) {

        console.log("网络请求错误！");
        return;
      }
      if (res.data.status != 200) {
        console.log("请求数据错误");
        return;
      }
      console.log('图片转文字', res)

      if (res.data.data.length > 0 && res.data.data[0] &&  res.data.data[0].length == 17) {
        let attr = this.data.vinBoxList
        console.log(res.data.data[0].split(''))
        res.data.data[0].split('').forEach((item, index) => {
          console.log(index)
          attr[index].val = item
        })
        console.log(attr)
        this.setData({
          vin: res.data.data[0],
          vinBoxList: attr,
          imgLoad: false,
        })
        this.goCategory()

      } else {
        console.log(55555555)
        this.setData({
          returnList: [],
          imgLoad: false,
          notVinMore: true
        })
        setTimeout(() => {
          this.setData({
            notVinMore: false,
            inputFocus: true
          })
        }, 2000)

        // this.setData({
        //   returnMessage: "扫描图片未得到相应信息",
        //   queryModel: !this.data.queryModel
        // })
      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  // 对相同的数据去重
  removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  },
  delStoryItem(e) {

    let self = this

    this.removeByValue(this.data.vinStoryList, this.data.vinStoryList[e.currentTarget.dataset.index])


    let StoryItem = JSON.stringify(this.data.vinStoryList)

    wx.setStorageSync('StoryItem', StoryItem);//userId       

    this.queryVinStory()

  },
  queryVinStory() {
    let self = this

    wx.getStorage({
      key: 'StoryItem',
      success: function (res) {
        let StoryItem = JSON.parse(res.data)
        console.log('历史记录', StoryItem)
        StoryItem.forEach((item, index) => {
          Object.assign(item, { queryTime: self.getDateDiff(new Date(item.createTime).getTime()) })
        })
        self.setData({
          vinStoryList: StoryItem

        })

      }, fail() {

      }
    })
  },
  handleInpue(e) {
    this.setData({
      vin: e.detail.value
    })
    if (this.data.vin.length == 17) {
      this.goCategory()
    }
  },

  // 设置车型并且插入历史跳转
  setModelIdlinkVinFilter(e) {
    if (e.currentTarget.dataset.modelid) {


      let modelVin = this.data.vinStoryList

      let vinNum = 0
      let a = {
        createTime: new Date(),
        vin: this.data.vin,
        brand: this.data.returnList[e.currentTarget.dataset.index].brand,
        model: this.data.returnList[e.currentTarget.dataset.index].model,
        model_id: this.data.returnList[e.currentTarget.dataset.index].model_id,
        pic: this.data.returnList[e.currentTarget.dataset.index].pic
      }

      modelVin.forEach((model, modelIndex) => {
        if (model.model_id == a.model_id) {
          this.removeByValue(modelVin, model)
        }
      });

      if (modelVin.length > 30) {
        this.removeByValue(modelVin, modelVin[modelVin.length - 1])
      }
      console.log(vinNum)
      modelVin.unshift(a)
      //LHGcP168288027506
      modelVin.forEach((item, index) => {
        if (item.vin == a.vin) {
          vinNum++
        }
      })
      console.log(vinNum)
      if (vinNum > 1) {
        modelVin.forEach((item, index) => {
          if (item.vin == a.vin) {
            vinNum = 0
            this.removeByValue(modelVin, item)
          }
        })
      }
      let StoryItem = JSON.stringify(modelVin)

      wx.setStorageSync('StoryItem', StoryItem);//userId       



      this.setModelIdByVin(e.currentTarget.dataset.modelid)

    }

  },
  // 列表点击设置车型并且跳转
  setModelId(e) {
    this.setModelIdByVin(e.currentTarget.dataset.modelid)

  },


  setModelIdByVin(model_id) {

    app.globalData.carId = model_id
    wx.navigateTo({
      url: '../../order_result/order_result?pageType=vin'
    })
    // wx.redirectTo({
    //   url: '../category/category',
    //   success: function (res) {

    //   },
    //   fail: function (res) { },
    //   complete: function (res) { },
    // })

  },

  close() {
    this.setData({ queryModel: !this.data.queryModel })
  },
  // 根据时间戳得到相应的时间 
  getDateDiff(dateTimeStamp) {
    var result;
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - dateTimeStamp;
    if (diffValue < 0) {
      return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    if (monthC >= 1) {
      if (monthC <= 12)
        result = "" + parseInt(monthC) + "月前";
      else {
        result = "" + parseInt(monthC / 12) + "年前";
      }
    }
    else if (weekC >= 1) {
      result = "" + parseInt(weekC) + "周前";
    }
    else if (dayC >= 1) {
      result = "" + parseInt(dayC) + "天前";
    }
    else if (hourC >= 1) {
      result = "" + parseInt(hourC) + "小时前";
    }
    else if (minC >= 1) {
      result = "" + parseInt(minC) + "分钟前";
    } else {
      result = "刚刚";
    }
    console.log(result)
    return result;
  },
  goCategory() {


    if (this.data.vin === '' || this.data.vin.length < 17) {
      this.setData({
        returnMessage: '请输入17位车架号',
        queryModel: !this.data.queryModel,
        isKeyboard: false
      })
      return;
    }




    wx.showLoading({
      mask: true,
      title: '加载中'
    })

    this.setData({
      returnList: []
    })
    let self = this
    let url = app.globalData.baseUrl1 + '/vin/qurey'
    let data = {
      merchantId: app.globalData.merchant.merchantId,
      vin: this.data.vin
    }
    console.log(data, 'data')
    //发起网络请求
    let callBack = (res) => {
      wx.hideToast()
      wx.hideLoading()
      if (res == null) {
        console.log("网络请求错误！");
        return;
      }
      if (res.data.status != 200) {

        wx.hideLoading()
        

        




        console.log("请求数据错误");
        console.log(this.data.queryModel)
        wx.showToast({
          icon: 'none',
          duration: 3000,
          title: res.data.message,
        })
        // this.setData({
        //   returnMessage: res.data.message,
        //   queryModel: !this.data.queryModel
        // })
        return;
      }

      if (res.data.status === 200) {
        console.log('查询vin', res.data.data)

        wx.hideLoading()
        if (res.data.data.length === 0) {
          this.setData({
            returnMessage: "未查询到相应信息",
            queryModel: !this.data.queryModel
          })
        } else if (res.data.data.length === 1) {
          let modelVin = this.data.vinStoryList



          let a = {
            createTime: new Date(),
            vin: this.data.vin,
            brand: res.data.data[0].brand,
            model: res.data.data[0].model,
            model_id: res.data.data[0].model_id,
            pic: res.data.data[0].pic
          }
          modelVin.forEach((model, modelIndex) => {
            if (model.model_id == a.model_id) {
              this.removeByValue(modelVin, model)

            }
          });
          if (modelVin.length > 30) {
            this.removeByValue(modelVin, modelVin[modelVin.length - 1])
          }

          modelVin.unshift(a)

          let StoryItem = JSON.stringify(modelVin)
          wx.setStorageSync('StoryItem', StoryItem);//userId       

          this.setModelIdByVin(res.data.data[0].model_id)


        } else if (res.data.data.length > 1) {
          this.setData({
            returnMessage: "匹配到以下结果，请选择查看",
            returnList: res.data.data,
            queryModel: !this.data.queryModel
          })
        }
      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowWidth)
        console.log(res.windowHeight)
        _this.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        })

      }
    })
    if (app.globalData.merchant === null) {
      app.doLogin(this.onLoad, this.onShow, options);
      return
    }
    this.setData({
      themeColors: app.globalData.merchant.themeColors
    })
    console.log(wx.getStorageSync('tempFilePath'))

    this.queryVinStory()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    console.log(e)
    if (wx.getStorageSync('tempFilePath')) {
      this.setData({
        imgLoad: true,
        vin: '',
        imgIcon: wx.getStorageSync('tempFilePath')
      })
      wx.removeStorageSync('tempFilePath')
      this.getCropperImg(this.data.imgIcon)
      //this.imageToText()
    }
    if (app.globalData.merchant.mustLogin && app.globalData.userId === null) {
      wx.navigateTo({
        url: '/pages/core/login/login',
        success() {
          wx.showToast({
            title: '请先登陆',
            icon: 'loading',
            duration: 1000
          })
        }
      })
      return
    }
    // 检查当前是否有是拍照页面回来

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
    * 输入框显示键盘状态
    */
  showKeyboard: function () {
    var self = this;
    let data = this.data.vinBoxList
    console.log()
    if (!data.filter((item) => { return item.select }).length) {
      data[0].select = true
    }

    self.setData({
      isKeyboard: true,
      specialBtn: true,
      tapNum: true,
      vinBoxList: data
    });
  },

  // 点击某个vin框
  selectVinItem(e) {
    console.log(e)
    let data = this.data.vinBoxList
    data.forEach((item) => {
      item.select = false
    })
    data[e.currentTarget.dataset.index].select = true
    this.setData({
      vinBoxList: data
    })

  },
  /**
     * 键盘事件
     */
  tapKeyboard: function (e) {
    var self = this;
    //获取键盘点击的内容，并将内容赋值到textarea框中
    var tapIndex = e.target.dataset.index;
    var tapVal = e.target.dataset.val;
    var keyboardValue;
    let vinList = self.data.vinBoxList
    let numVin = this.data.numVin
    if (tapVal == '巛') {
      //说明是删除
      vinList.forEach((item, i) => {
        if (item.select) {
          item.val ? self.data.textArr.splice(i, 1) : self.data.textArr.splice(i - 1, 1)
        }
      })
      self.data.textArr = []
      vinList.forEach((item, i) => {
        if (item.select) {
          if (item.val) {
            vinList[i].val = ''
            return
          }
          if (vinList[i - 1]) {
            vinList[i - 1].select = true
            vinList[i - 1].val = ''
            vinList[i].select = false
          }
          return
        }
        self.data.textArr.push(vinList[i].val)
      })
      self.data.textValue = self.data.textArr.join('');
      console.log()
      numVin = vinList.filter((item) => { return item.val }).length
      self.setData({
        textValue: self.data.textValue,
        vinBoxList: vinList,
        numVin: numVin
      });
      return false;
    }
    console.log()
    if (tapVal == 'Q' || tapVal == 'I' || tapVal == 'O') {
      return
    }
    let indexs = ''
    vinList.forEach((item, cel) => {
      if (item.select) {
        indexs = cel
      }
    })
    if (indexs < 17) {
      if (!vinList[indexs].val) {
        vinList[indexs].val = tapVal
        if (vinList[indexs + 1]) {
          vinList[indexs].select = false
          vinList[indexs + 1].select = true
        }
      } else {
        vinList[indexs].val = tapVal
        if (vinList[indexs + 1]) {
          vinList[indexs].select = false
          vinList[indexs + 1].select = true
        }
      }
    }
    numVin = vinList.filter((item) => { return item.val }).length
    self.setData({
      textValue: self.data.textValue,
      keyboardValue: self.data.keyboard2,
      specialBtn: true,
      vinBoxList: vinList,
      numVin: numVin
    });
    if (numVin == 17) {
      self.setData({
        isKeyboard: false,
      })
      //self.tapSpecBtn()

    }
    if (self.data.textArr.length > 1) {
      //展示数字键盘
      self.setData({
        tapNum: true
      });
    }
  },
  // 键盘完成事件
  tapSpecBtn(e) {
    console.log(e)
    let vals = ''
    this.data.vinBoxList.forEach((item) => {
      if (item.val) {
        vals += item.val
      }
    })
    console.log(vals)
    if (e != undefined && e.currentTarget.dataset.val == '完成') {
      this.setData({
        isKeyboard: false
      })
      return
    }
    if (vals.length < 17) {
      wx.showToast({
        icon: 'none',
        title: '请正确输入17位车架号',
      })
      return
    }

    console.log(vals)
    // 直接调查询vin接口
    this.setData({
      isKeyboard: false,
      vin: vals
    })
    this.goCategory()

  }
})
/**
* fn:延时调用函数
* delay:延迟多长时间
* mustRun:至少多长时间触发一次
*/
var throttle = function (fn, delay, mustRun) {
  var timer = null,
    previous = null;

  return function () {
    var now = +new Date(),
      context = this,
      args = arguments;
    if (!previous) previous = now;
    var remaining = now - previous;
    if (mustRun && remaining >= mustRun) {
      fn.apply(context, args);
      previous = now;
    } else {
      clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);

    }
  }
}

var touchMove = function (_this, e) {
  //触摸移动中
  if (e.touches.length === 1) {
    //单指移动
    if (_this.data.stv.zoom) {
      //缩放状态，不处理单指
      return;
    }
    let { clientX, clientY } = e.touches[0];
    let offsetX = clientX - _this.startX;
    let offsetY = clientY - _this.startY;
    _this.startX = clientX;
    _this.startY = clientY;
    let { stv } = _this.data;
    stv.offsetX += offsetX;
    stv.offsetY += offsetY;
    stv.offsetLeftX = -stv.offsetX;
    stv.offsetLeftY = -stv.offsetLeftY;
    _this.setData({
      stv: stv
    });

  } else if (e.touches.length === 2) {
    //计算旋转
    let preTwoPoint = JSON.parse(JSON.stringify(twoPoint))
    twoPoint.x1 = e.touches[0].pageX * 2
    twoPoint.y1 = e.touches[0].pageY * 2
    twoPoint.x2 = e.touches[1].pageX * 2

    function vector(x1, y1, x2, y2) {
      this.x = x2 - x1;
      this.y = y2 - y1;
    };

    //计算点乘
    function calculateVM(vector1, vector2) {
      return (vector1.x * vector2.x + vector1.y * vector2.y) / (Math.sqrt(vector1.x * vector1.x + vector1.y * vector1.y) * Math.sqrt(vector2.x * vector2.x + vector2.y * vector2.y));

    }
    //计算叉乘
    function calculateVC(vector1, vector2) {
      return (vector1.x * vector2.y - vector2.x * vector1.y) > 0 ? 1 : -1;
    }

    let vector1 = new vector(preTwoPoint.x1, preTwoPoint.y1, preTwoPoint.x2, preTwoPoint.y2);
    let vector2 = new vector(twoPoint.x1, twoPoint.y1, twoPoint.x2, twoPoint.y2);
    let cos = calculateVM(vector1, vector2);
    let angle = Math.acos(cos) * 180 / Math.PI;

    let direction = calculateVC(vector1, vector2);
    let _allDeg = direction * angle;


    // 双指缩放
    let xMove = e.touches[1].clientX - e.touches[0].clientX;
    let yMove = e.touches[1].clientY - e.touches[0].clientY;
    let distance = Math.sqrt(xMove * xMove + yMove * yMove);

    let distanceDiff = distance - _this.data.stv.distance;
    let newScale = _this.data.stv.scale + 0.005 * distanceDiff;

    if (Math.abs(_allDeg) > 1) {
      _this.setData({
        'stv.rotate': _this.data.stv.rotate + _allDeg
      })
    } else {
      //双指缩放
      let xMove = e.touches[1].clientX - e.touches[0].clientX;
      let yMove = e.touches[1].clientY - e.touches[0].clientY;
      let distance = Math.sqrt(xMove * xMove + yMove * yMove);

      let distanceDiff = distance - _this.data.stv.distance;
      let newScale = _this.data.stv.scale + 0.005 * distanceDiff;
      if (newScale < 0.2 || newScale > 2.5) {
        return;
      }
      console.log(newScale)
      _this.setData({
        'stv.distance': distance,
        'stv.scale': newScale,
      })
    }
  } else {
    return;
  }
}

//为touchMove函数节流
const fn = throttle(touchMove, 10, 10);